package com.inibb.app.service.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.inibb.app.converter.Db2VOConverter;
import com.inibb.app.converter.NoteConvertor;
import com.inibb.app.dao.JpaGenericDao;
import com.inibb.app.dao.api.IDao;
import com.inibb.app.pagination.dto.PaginationCriteria;
import com.inibb.app.po.Note;
import com.inibb.app.service.INoteService;
import com.inibb.app.util.Sys;
import com.inibb.app.vo.NoteSC;
import com.inibb.app.vo.NoteVO;

@Service
@Transactional
public class NoteServiceImpl implements INoteService{
	
	private IDao<Note, Integer> noteDao;
	
	@PersistenceContext(unitName = "entityManager")
	private EntityManager entityManager ;
	
	@Autowired
	public void setEntityManagerFactory() {
		noteDao = new JpaGenericDao<Note, Integer>( entityManager,Note.class);
	}
	
	@Override
	public NoteVO getNote(Integer noteId){
		Note n = noteDao.get(noteId);
		if(n==null)
			return null;
		return NoteConvertor.converPO2VO(n);
		
	}
	
	@Override
	public void delete(Integer noteId) {
		noteDao.delete(noteId);
	}

	@Override
	public void saveOrUpdate(NoteVO vo){
		if(vo.getNoteId()==null){
			vo.setCreatedBy(1);
			vo.setCreatedDate(Sys.getDate());
			noteDao.persist(NoteConvertor.converVO2PO(vo));
		}else{
			vo.setUpdatedBy(1);
			vo.setUpdatedDate(Sys.getDate());
			noteDao.merge(NoteConvertor.converVO2PO(vo));
		}
	}
	public int countPageNotes(NoteSC paginationCriteria) {
		BigInteger total = (BigInteger) noteDao.queryNativeSqlForObject("admin", "countPageNotes", paginationCriteria);
		
		return total.intValue();
	}

	public List<NoteVO> searchPageNotes(NoteSC paginationCriteria) {
		List<Object[]> list = (List<Object[]>) noteDao.queryNativeSqlForList("admin", "searchPageNotes", paginationCriteria);
		List<NoteVO> gcList = new ArrayList<NoteVO>();
		for(Object[] obj:list){
			gcList.add(Db2VOConverter.toVO4Note(obj));
		}
		return gcList;
	}
	public int countPageNotes(PaginationCriteria paginationCriteria) {
		BigInteger total = (BigInteger) noteDao.queryNativeSqlForObject("admin", "countPageNotes", paginationCriteria);
		
		return total.intValue();
	}

	public List<NoteVO> searchPageNotes(PaginationCriteria paginationCriteria) {
		List<Object[]> list = (List<Object[]>) noteDao.queryNativeSqlForList("admin", "searchPageNotes", paginationCriteria);
		List<NoteVO> gcList = new ArrayList<NoteVO>();
		for(Object[] obj:list){
			gcList.add(Db2VOConverter.toVO4Note(obj));
		}
		return gcList;
	}
}
